//package com.czr.controller;
//
//import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.core.toolkit.StringUtils;
//import com.czr.constant.isLogin;
//import com.czr.dao.service.CzrUserService;
//import com.czr.dto.WxParam;
//import com.czr.util.HttpClientUtil;
//import com.czr.vo.Result;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiImplicitParam;
//import io.swagger.annotations.ApiImplicitParams;
//import io.swagger.annotations.ApiOperation;
//import lombok.extern.slf4j.Slf4j;
//import org.dom4j.io.SAXReader;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.ApplicationArguments;
//import org.springframework.boot.ApplicationRunner;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.io.PrintWriter;
//import java.security.MessageDigest;
//import java.security.NoSuchAlgorithmException;
//import java.sql.SQLException;
//import java.util.Arrays;
//import java.util.Enumeration;
//import java.util.Map;
//
//@Slf4j
//@Api(value = "微信公众号授权", tags = "微信公众号授权")
//@RestController
//@RequestMapping("/weChat")
//public class WeChatController implements ApplicationRunner {
//
//
//    @Autowired
//    private CzrUserService userService;
//    String appid = "wx9cbc97064b351265";
//    String secret = "6a4d7a0243b4aa4c4a512f800507af89";
//
//    String str = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&grant_type=authorization_code&code=";
//
//    private static String access_token = "";
//    private static String jsapi_ticket = "";
//
//    //拉取授权
//    //location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9cbc97064b351265&redirect_uri="+encodeURIComponent(local)+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
//
//    //获取openid
//    @ApiOperation(value = "获取openid（用户唯一识别号）", notes = "获取openid（用户唯一识别号）")
//    @ApiImplicitParams({
//            //参数效验
//            @ApiImplicitParam(name="code",value="微信授权码",required=true,dataType="string")
//    })
//    @GetMapping("/getUserInfo")
//    public Result<Object> getUserInfo(@RequestParam String code){
//
//        String body = HttpClientUtil.doGet(str+code);
//        log.info("获取微信access_token返回信息为：{}",body);
//        if(StringUtils.isNotBlank(body)){
//            JSONObject obj = JSONObject.parseObject(body);
//            if(obj.get("errcode")!=null){
//                return Result.fail(obj.getString("errmsg"));
//            } else {
//                String access_token = obj.getString("access_token");
//                String openid = obj.getString("openid");
//                String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
//                String result = HttpClientUtil.doGet(url);
//                log.info("获取微信用户信息返回值为：{}",result);
//                if(StringUtils.isNotBlank(result)){
//                    JSONObject object = JSONObject.parseObject(result);
//                    if(object.get("errcode")!=null){
//                        return Result.fail(object.getString("errmsg"));
//                    } else {
//                        return Result.data(object);
//                    }
//                }
//            }
//        }
//        return Result.fail("返回信息为空");
//    }
//
////    @ApiOperation(value = "此接口不用", notes = "此接口不用")
////    @GetMapping("/getWxUnionId")
////    public Result<Object> getWxUnionId(@RequestParam String openid){
////
////        String url = "https://api.weixin.qq.com/cgi-bin/user/info?lang=zh_CN&access_token="+access_token+"&openid="+openid;
////        String result = HttpClientUtil.doGet(url);
////        log.info("获取微信用户信息返回值为：{}",result);
////        if(StringUtils.isNotBlank(result)){
////            JSONObject object = JSONObject.parseObject(result);
////            if(object.get("errcode")!=null){
////                return Result.fail(object.getString("errmsg"));
////            } else {
////                return Result.data(object);
////            }
////        }
////
////        return Result.fail("返回信息为空");
////    }
//
//
//    public void getWxAccessToken(){
//
//        String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
//        String body = HttpClientUtil.doGet(access_token_url);
//        log.info("获取微信全局access_token返回信息为：{}",body);
//        if(StringUtils.isNotBlank(body)){
//            JSONObject obj = JSONObject.parseObject(body);
//            if(obj.get("errcode")==null){
//                access_token =  obj.getString("access_token");
//            }
//        }
//
//    }
//
//    public void getWxJsapiTicket(){
//
//        String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + access_token;
//        String body = HttpClientUtil.doGet(jsapi_ticket_url);
//        log.info("获取微信全局jsapi_ticket返回信息为：{}",body);
//        if(StringUtils.isNotBlank(body)){
//            JSONObject obj = JSONObject.parseObject(body);
//            if(obj.get("errcode")!=null && obj.get("errmsg").equals("ok")){
//                jsapi_ticket =  obj.getString("ticket");
//            }
//        }
//
//    }
//
//    @isLogin
//    @ApiOperation(value = "获取签名等信息", notes = "获取签名等信息")
//    @GetMapping("getWxSignature")
//    public JSONObject getWxSignature(@RequestParam String ymurl) throws SQLException {
//
//        String timestamp = (System.currentTimeMillis() / 1000) + "";//时间戳
//        String noncestr = "CZRQMC";//生成签名的随机串
//        String signature = getSignature(ymurl, timestamp, noncestr, jsapi_ticket);//生成微信JS SDK签名的方法
//        JSONObject jo = new JSONObject();
//        jo.put("timestamp", timestamp);//生成签名的时间戳
//        jo.put("noncestr", noncestr);//生成签名的随机串
//        jo.put("signature", signature);//生成的签名
//        return jo;
//
//    }
//
//
//    /*
//     * 微信JSSDK算法
//     * */
//    private String getSignature(String ymurl, String timestamp, String noncestr,String jsapiTicket) throws SQLException {
//
//        String string1 = "jsapi_ticket=" + jsapiTicket
//                + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url="
//                + ymurl;
//        log.info("微信JSSDK算法生成Signature入参{}",string1);
//        return sha1(string1);
//    }
//
//
//    public static String sha1(String str) {
//        try {
//            MessageDigest digest = MessageDigest.getInstance("SHA-1");
//            digest.update(str.getBytes());
//            byte messageDigest[] = digest.digest();
//            // Create Hex String
//            StringBuffer hexString = new StringBuffer();
//            // 字节数组转换为 十六进制 数
//            for (int i = 0; i < messageDigest.length; i++) {
//                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
//                if (shaHex.length() < 2) {
//                    hexString.append(0);
//                }
//                hexString.append(shaHex);
//            }
//            return hexString.toString();
//
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        return "";
//    }
//
////
////    @ApiOperation(value = "此接口不用", notes = "此接口不用")
////    @PostMapping("/forwardingInterface")
////    @ResponseBody
////    public Result<Object> forwardingInterface(@RequestBody forwardingParam entity) throws Exception {
////        if(ObjectUtils.isEmpty(entity)){
////            throw new Exception("请求参数为空");
////        }
////
////
////        log.info(entity.getForwardingUrl());
////        log.info(entity.getForwardingType());
////        log.info(entity.getParams().toString());
////
////        return Result.data(null);
////    }
//
//
////    @ApiOperation(value = "此接口不用", notes = "此接口不用")
////    @PostMapping("/disNetwork")
////    @ResponseBody
////    public Result<Object> disNetwork(@RequestBody disNetworkParam entity) throws Exception {
////        if(ObjectUtils.isEmpty(entity)){
////            throw new Exception("请求参数为空");
////        }
////
////
////        log.info(entity.getWifiName());
////        log.info(entity.getWifiPwd());
////        log.info(entity.getOpenId());
////
////        return Result.data(entity.getWifiName());
////    }
//
//
//    @Override
//    public void run(ApplicationArguments args) throws Exception {
//        this.getWxAccessToken();
//        this.getWxJsapiTicket();
//    }
//
//
//    @isLogin
//    @ApiOperation(value = "绑定微信", notes = "绑定微信（微信公众号）")
//    @PostMapping("/bindingWx")
//    public Result<Map<String, Object>> bindingWx(@RequestBody WxParam wxParam) {
//        try {
//            Result<Map<String, Object>> result = userService.bindingWx(wxParam);
//            return result;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.fail();
//        }
//    }
//    @isLogin
//    @ApiOperation(value = "微信登录接口", notes = "登录接口")
//    @PostMapping("/wxLogin")
//    public Result<Map<String, Object>> wxLogin(@RequestParam String openId) {
//        try {
//            Result<Map<String, Object>> result = userService.wxLogin(openId);
//            return result;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.fail();
//        }
//
//    }
//
//    @isLogin
//    @ApiOperation(value = "解绑微信", notes = "解绑微信（微信公众号）")
//    @PostMapping("/unbindingWx")
//    public Result<Map<String, Object>> unbindingWx(@RequestBody WxParam wxParam) {
//        try {
//            Result<Map<String, Object>> result = userService.unbindingWx(wxParam);
//            return result;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.fail();
//        }
//    }
//
//    @isLogin
//    @PostMapping(value = "/checkToken",produces = "text/html;charset=utf-8")
//    public String messageHandle(HttpServletRequest request, HttpServletResponse response) {
//        try {
//            return userService.messageHandle(request,response);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//    private Logger logger = LoggerFactory.getLogger(WeChatController.class);
//    private static final String TOKEN = "tokenxxx";
//    @isLogin
//    @GetMapping(value = "/checkToken",produces = "text/html;charset=utf-8")
//    public String checkToken(@RequestParam("signature") String signature,@RequestParam("timestamp") String timestamp,
//                             @RequestParam("nonce") String nonce,@RequestParam("echostr") String echostr) {
//        //排序
//        String[] arr = {TOKEN, timestamp, nonce};
//        Arrays.sort(arr);
//
//        StringBuilder content = new StringBuilder();
//        for (int i = 0; i < arr.length; i++) {
//            content.append(arr[i]);
//        }
//
//        //sha1Hex 加密
//        MessageDigest md = null;
//        String temp = null;
//        try {
//            md = MessageDigest.getInstance("SHA-1");
//            byte[] digest = md.digest(content.toString().getBytes());
//            temp = byteToStr(digest);
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        if ((temp.toLowerCase()).equals(signature)){
//            return echostr;
//        }
//        return null;
//    }
//    private static String byteToStr(byte[] byteArray){
//        String strDigest = "";
//        for (int i = 0; i < byteArray.length; i++) {
//            strDigest += byteToHexStr(byteArray[i]);
//        }
//        return strDigest;
//    }
//
//    private static String byteToHexStr(byte mByte){
//        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','B', 'C', 'D', 'E', 'F' };
//        char[] tempArr = new char[2];
//        tempArr[0] = Digit[(mByte >>> 4)& 0X0F];
//        tempArr[1] = Digit[mByte & 0X0F];
//        String s = new String(tempArr);
//        return s;
//    }
//}
